package tools

import (
	"log"
	"strconv"

	gosocketio "github.com/graarh/golang-socketio"
	"github.com/graarh/golang-socketio/transport"
	socketio_client "github.com/zhouhui8915/go-socket.io-client"
)

/*
 +----------------------------------------------------------------------
 + Title        : socketioClient
 + Author       : huwl
 + Version      : 1.0.0
 + Initial-Time : 2024-09-22
 + Last-time    : 这个文件最后修改的时间 + 修改人的名称
 + Desc         : socketio 客户端
 + Desc         : 包括：github.com/graarh/golang-socketio 有关闭功能
 + Desc         : 安装：go get github.com/graarh/golang-socketio
 +
 + Desc         : 包括：github.com/zhouhui8915/go-socket.io-client 没有关闭功能
 + Desc         : 安装：go get github.com/zhouhui8915/go-socket.io-client
 +----------------------------------------------------------------------
*/

type SocketioClient struct {
	Client           *socketio_client.Client
	GosocketioClient *gosocketio.Client
}

/**
 * 创建 SOCKETIO CLIENT
 *
 * @return *SocketioClient
 * @author huwl
 */
func NewSocketioClient(mode int) (*SocketioClient, error) {
	opts := &socketio_client.Options{
		Transport: "websocket",
		Query: map[string]string{
			"username": "golang 客户端",
		},
	}

	var err error

	sockerConfig, err := GetConfig("socket-io", "yml")
	if err != nil {
		return nil, err
	}

	socketioClient := &SocketioClient{}

	url := sockerConfig.GetString(Env + ".url")
	port := sockerConfig.GetInt(Env + ".port")

	if mode == 1 {
		client, err := socketio_client.NewClient("http://"+url+strconv.Itoa(port)+"/socket.io/", opts)
		if err != nil {
			return nil, err
		}

		socketioClient.Client = client

		// 监听连接
		socketioClient.OnConn()

		// 监听消息
		socketioClient.OnMessage()

		// 监听错误
		socketioClient.OnErr()

		// 监听断开
		socketioClient.OnConn()
	} else {
		gosocketioClient, err := gosocketio.Dial(
			gosocketio.GetUrl(url, port, false),
			transport.GetDefaultWebsocketTransport(),
		)
		if err != nil {
			return nil, err
		}

		socketioClient.GosocketioClient = gosocketioClient
	}

	return socketioClient, nil
}

/**
 * 监听连接
 *
 * @author huwl
 */
func (client *SocketioClient) OnConn() {
	client.Client.On("connection", func() {
		log.Println(" ----------------- 开始监听连接 ----------------- ")
	})
}

/**
 * 监听消息
 *
 * @author huwl
 */
func (client *SocketioClient) OnMessage() {
	client.Client.On("message", func() {
		log.Println(" ----------------- 开始监听消息 ----------------- ")
	})
}

/**
 * 监听错误
 *
 * @author huwl
 */
func (client *SocketioClient) OnErr() {
	client.Client.On("error", func() {
		log.Println(" ----------------- 开始监听错误 ----------------- ")
	})
}

/**
 * 监听断开
 *
 * @author huwl
 */
func (client *SocketioClient) OnDisconn() {
	client.Client.On("disconnection", func() {
		log.Println(" ----------------- 开始监听断开 ----------------- ")
	})
}
